import React, {Component} from 'react';
import {connect}                from 'react-redux';
import {Field, reduxForm, initialize, change, formValueSelector}     from 'redux-form';
import Button                   from '../components/Button';
import Form                     from '../components/Form';
import Modal                    from '../components/Modal';
import api                      from '../../api';

@connect(
	function () {
		return {};
	},
	{initialize}
)
@reduxForm({
	form: 'resetPasswordForm',  // a unique identifier for this form
	validate(values) {
		const errors = {};
		if (!values.oldPassword) errors.oldPassword = '必填字段';
		if (!values.newPassword) errors.newPassword = '必填字段';
		if (values.newPassword != values.confirmPassword) errors.confirmPassword = '密码不一致';
		if (!values.confirmPassword) errors.confirmPassword = '必填字段';

		return errors
	},
	asyncValidate(values) {
		return api.getTestPassword({password: values.oldPassword}).then((resp)=> {
			if (!resp) throw {oldPassword: '密码不正确，请重新输入！'}
		});
	},
	asyncBlurFields: ['oldPassword']
})
class Security extends Component {
	handleSubmit(values) {
		api.putResetPassword(values).then((resp)=> {
			this.props.initialize({});
			Modal.message.success("修改密码成功!");
		}).catch((error)=> {
			Modal.show((
				<div style={{color: '#ff6633'}}>
					<h2>修改密码失败</h2>
					<p>{error.message}</p>
				</div>
			));
		});
	}

	render() {
		const {handleSubmit} = this.props;
		return (
			<Form className="form" onSubmit={handleSubmit(this.handleSubmit.bind(this)) }>
				<Field name="oldPassword" type="password" component={Form.renderInputField} label="密码"/>
				<Field name="newPassword" type="password" component={Form.renderInputField} label="新密码"/>
				<Field name="confirmPassword" type="password" component={Form.renderInputField} label="确认密码"/>

				<div className="form-field">
					<label/>
					<div className="form-field-wrapper">
						<Button type="submit">提交</Button>
					</div>
				</div>
			</Form>
		);
	}
}

export default Security;